;!function (win, doc) {
    layui.config({
        base: '/statics/admin/' //静态资源所在路径
    }).extend({
        //主入口模块
        index: 'lib/index',
        NavBarSide: 'pkcms/NavBarSide',
        selectN: 'xmSelect/selectN',
        selectM: 'xmSelect/selectM',
        xmSelect: 'xmSelect/xm-select',
        dtree: 'dtree/dtree',
        step: 'step-lay/step'
    }).use('index', function () {

    });

    var PKLayer = function (url_login) {
        this.url_login = url_login;
    }, config = {
        baiDuMaps: {
            initPoint: {
                lat: 120.69,
                lng: 27.99
            }
        },
        DISABLED: 'layui-btn-primary layui-disabled'
    }, tipsMsg = function (str) {
        layer.msg(str, {offset: 't'});
    }, tipsAlert = function (str, icon) {
        layer.alert(str, {offset: 't', anim: 5, icon: icon});
    }, tipsConfirm = function (str, fn) {
        layer.msg(str, {
            time: 30000, offset: 't', anim: 5,
            btn: ['确定', '取消'],
            yes: function () {
                fn();
            },
            btn2: function () {
                layer.closeAll();
            }
        });
    }, apiPost = function (api_url, api_params, fn) {
        let api_root = '/index.php/';
        if (api_url.indexOf(api_root) === -1) {
            api_url = api_root + api_url;
        }
        PKCms.apiPost(api_url, api_params, function (error, apiResult) {
            if (error) {
                if (typeof error == "string") {
                    tipsMsg(error);
                } else {
                    alert('接口：' + api_url + ' 请求不正常');
                }
            } else {
                apiResultHandler(apiResult, function (resData, resCount) {
                    fn(resData, resCount);
                });
            }
        });
    }, apiResultHandler = function (apiResult, fn) {
        PKCms.apiResultHandler(apiResult, function (errMsg, errCode, resData, resCount) {
            if (errCode === 401) {
                win.location.href = this.url_login;
            } else if (errMsg) {
                tipsMsg(errMsg);
                let domBtn_stop = layui.$('.layui-form-footer-fixed #steps');
                if (domBtn_stop.length === 1) {
                    domBtn_stop.hide();
                    layui.$('#btnBar').show();
                }
            } else {
                fn(resData, resCount);
            }
        })
    }, apiGet = function (api_url, api_params, fn) {
        let api_root = '/index.php/';
        if (typeof api_url == "undefined") {
            console.warn('请求的地址为空', api_params);
        } else {
            if (typeof api_url == "string" && api_url.indexOf(api_root) === -1) {
                api_url = api_root + api_url;
            }
            PKCms.apiGet(api_url, api_params, function (error, apiResult) {
                if (error) {
                    if (typeof error == "string") {
                        tipsMsg(error);
                    } else {
                        alert('接口：' + api_url + ' 请求不正常');
                    }
                } else {
                    PKCms.apiResultHandler(apiResult, function (errMsg, errCode, resData, resCount) {
                        if (errCode === 401) {
                            win.location.href = this.url_login;
                        } else if (errMsg) {
                            tipsMsg(errMsg);
                        } else {
                            fn(resData, resCount);
                        }
                    })
                }
            });
        }
    }, useForm = function (onFormFn) {
        if ($('[lay-filter="form-element"]').length > 0 ||
            $('[lay-filter="form-frame"]').length > 0 ||
            $('[lay-filter="form-page"]').length > 0) {
            var dom_tplId = 'tpl-form';
            var dom_viewId = 'view-form';
            var dom_tpl = $('#' + dom_tplId);
            if (dom_tpl.length === 1) {
                var api_url = dom_tpl.data('api');
                var api_params = {id: dom_tpl.data('id')};
                if (api_params.id === 0) {
                    useTpl({}, dom_tplId, function (html, tpl) {
                        doc.getElementById(dom_viewId).innerHTML = html;
                        onFormFn();
                    });
                } else if (typeof api_url != "undefined") {
                    apiGet(
                        api_url + '/ApiGetDetail', api_params,
                        function (apiResult, count) {
                            useTpl(apiResult, dom_tplId, function (html, tpl) {
                                doc.getElementById(dom_viewId).innerHTML = html;
                                onFormFn();
                            });
                        }
                    );
                }
            } else {
                onFormFn();
            }
        }
    }, useFormControlByBDMaps = function (mapContainerId, inputId) {
        mapContainerId = 'baiduMap_' + mapContainerId;
        var value = $(inputId).val();
        var init_point;
        if (value !== '' && value.indexOf(',') > 0) {
            value = value.split(',');
            init_point = baiDuMaps_checkLatAndLong(value[0], value[1]);
        } else {
            init_point = config.baiDuMaps.initPoint;
        }
        console.log('init_point', init_point);
        PKCms.useBDMapsJs(function () {
            useModelByBtn("百度地图定位选择器", ['800px', '505px'],
                "<div class=\"layui-form\">\n" +
                "    <div class=\"layui-form-item\">\n" +
                "        <input type=\"text\" class=\"layui-input\" id=\"map_keyword\" placeholder=\"请输入公司名或建筑名进行搜索\" value=\"\" />\n" +
                "    </div>\n" +
                "</div>" +
                "<div id='" + mapContainerId + "' style='width: 100%;height: 350px;overflow: hidden;margin: 0;'></div>",
                function (index) {
                    // 百度地图API功能
                    // 创建地图实例
                    var map = new BMap.Map(mapContainerId);
                    //启用滚轮放大缩小
                    map.enableScrollWheelZoom();
                    map.addControl(new BMap.NavigationControl());
                    // 创建点坐标
                    var point = new BMap.Point(init_point.lat, init_point.lng);
                    map.centerAndZoom(point, 18);
                    // 创建标注
                    var marker = new BMap.Marker(map.getCenter());
                    // 将标注添加到地图中
                    map.addOverlay(marker);
                    //可拖拽
                    marker.enableDragging();
                    //跳动的动画
                    marker.setAnimation(BMAP_ANIMATION_BOUNCE);
                    map.addEventListener("click", function (e) {
                        // 单击地图获取坐标点；
                        // console.log('point', e.point);
                        //获取当前地理名称
                        var point = new BMap.Point(e.point.lng, e.point.lat);
                        var gc = new BMap.Geocoder();
                        gc.getLocation(point, function (rs) {
                            console.log('rs', rs)
                            // 获取具体的城市与街道地址
                            // var addComp = rs.addressComponents;
                            // console.log('addComp', addComp);
                            // $(inputId).val(rs.address + " " + rs.surroundingPois.length ? rs.surroundingPois[0].title : "")
                            //将输入框赋值
                            $(inputId).val(e.point.lng + "," + e.point.lat)
                        });
                        // map.panTo方法，把点击的点设置为地图中心点
                        map.panTo(new BMap.Point(e.point.lng, e.point.lat));
                    });
                    marker.addEventListener("dragend", function (e) {
                        //拖拽标注获取标注坐标
                        // console.log('当前位置', e.point);
                        //获取当前地理名称
                        var point = new BMap.Point(e.point.lng, e.point.lat);
                        var gc = new BMap.Geocoder();
                        gc.getLocation(point, function (rs) {
                            // 获取具体的城市与街道地址
                            // var addComp = rs.addressComponents;
                            // console.log('addComp', addComp);
                            // $(inputId).val(rs.address + " " + rs.surroundingPois ? rs.surroundingPois[0].title : "")
                            //将输入框赋值
                            $(inputId).val(e.point.lng + "," + e.point.lat)
                        });
                    })
                    //加载完成之后,改变标注点坐标,使之和当前定位的城市基本相符
                    map.addEventListener("tilesloaded", function () {
                        var newpoint = map.getCenter();
                        // console.log('newpoint', newpoint);
                        marker.setPosition(newpoint);
                    });
                    //定义地图搜索
                    var local = new BMap.LocalSearch(map, {
                        renderOptions: {
                            map: map
                            , panel: "r-result"
                        }
                        , onInfoHtmlSet: function (res) {
                            //通过搜索结果标记坐标
                            var lng = res.point.lng, lat = res.point.lat;
                            //清除覆盖物
                            map.removeOverlay(marker);
                            if (lng && lat) {
                                var point = new BMap.Point(lng, lat);
                                //创建标注
                                marker = new BMap.Marker(point);
                                //将标注添加到地图中
                                map.addOverlay(marker);
                                //跳起来
                                marker.setAnimation(BMAP_ANIMATION_BOUNCE);
                                $(inputId).val(lng + "," + lat)
                            }
                        }
                    });
                    $('#map_keyword').on('input propertychange', function () {
                        local.search($(this).val())
                    });
                },
                function (index) {
                    layer.close(index);
                });
        });
    }, useFormControlByBtnSubmit = function (fn, onDomBtn) {
        if (typeof onDomBtn == "undefined") {
            onDomBtn = 'lay-submit';
        }
        // console.log('onDomBtn', onDomBtn);
        let btnSubmit = $('button[' + onDomBtn + ']').attr('lay-filter');
        // console.log('btnSubmit', btnSubmit);
        layui.use(['form', 'dtree'], function () {
            var $ = layui.$
                , form = layui.form
                , dtree = layui.dtree;
            form.render();
            var dom_switch = $('[lay-skin="switch"]');
            if (dom_switch.length > 0) {
                dom_switch.each(function (index, element) {
                    var id = $(element).attr('id');
                    form.on('switch(' + id + ')', function (data) {
                        if (data.elem.checked) {
                            data.value = 1;
                            $('#' + id).attr('value', 1);
                        } else {
                            data.value = 0;
                            $('#' + id).attr('value', 0);
                        }
                    });
                });
            }
            form.on('submit(' + btnSubmit + ')', function (obj) {
                // console.log(btnSubmit);
                var dom_tree = $('.PK-Tree');
                var form_params = obj.field;
                if (dom_tree.length > 0) {
                    dom_tree.each(function (index, element) {
                        var domTree_id = $(element).attr('id');
                        var params = dtree.getCheckbarNodesParam(domTree_id);
                        form_params[domTree_id] = [];
                        for (let param of params) {
                            // console.log(param);
                            form_params[domTree_id].push(param.nodeId);
                        }
                    });
                }
                setTimeout(function () {
                    fn(form_params);
                }, 500);
                return false;
            });
        });
    }, useFormControlByColorPicker = function (domId, value) {
        layui.use(['colorpicker'], function () {
            var colorpicker = layui.colorpicker;
            colorpicker.render({
                elem: '#divColorPicker_' + domId,
                color: value,
                done: function (color) {
                    $('#inputColorPicker_' + domId).val(color);
                }
            });
        });
    }, useFormControlByDateTime = function (element) {
        layui.use('laydate', function () {
            var laydate = layui.laydate;
            laydate.render({
                elem: '#' + element.attr('id'),
                range: typeof element.data('range') !== "undefined",
                type: 'datetime'
            });
        });
    }, useFormControlBySelectMN = function (domId, list_data) {
        var dom = $('#' + domId), dom_name = dom.data('name')
            , dom_value = dom.data('value'), dom_type = dom.data('type');
        if (typeof dom_value != "undefined") {
            if (dom_type === 'checkbox') {
                if (typeof dom_value !== "string") {
                    dom_value = dom_value.toString();
                }
                dom_value = dom_value.split(',');
            } else {
                dom_value = [dom_value];
            }
        } else {
            dom_value = [];
        }
        layui.use(['selectM', 'selectN', 'form'], function () {
            var selectM = layui.selectM
                , selectN = layui.selectN;
            var options = {
                elem: '#' + domId,
                selected: dom_value,
                name: dom_name,
                filter: dom_name,
                search: false,
                data: list_data
            };
            if (dom_type === 'checkbox') {
                selectM(options);
            } else {
                selectN(options);
            }
        });
    }, useFormControlBySelect = function (domId) {
        var dom = $('#' + domId), source = dom.data('source')
            , api_url = dom.data('api'), api_params = dom.data('params');
        if (typeof source === "string") {
            useFormControlBySelectMN(domId, data[source]);
        } else {
            if (api_url.split('/').length < 3) {
                api_url += '/ApiBySelect';
            }
            if (typeof api_params != "undefined") {
                api_params = PKCms.urlVarsToJSON(api_params);
            }
            apiGet(api_url, api_params, function (apiResult, count) {
                useFormControlBySelectMN(domId, apiResult);
            });
        }
    }, useFormControlBySelectTree = function (domId, value, apiUrl) {
        layui.use(['xmSelect'], function () {
            apiGet(apiUrl + '/ApiBySelect', {}, function (apiResult, count) {
                useFormControlByXMSelect('#selectTree_' + domId, apiResult, value, true, true,
                    function (data) {
                        var value = 0;
                        if (data.length > 0) {
                            value = data[0].value;
                        }
                        $('#selectTree_hidden_' + domId).val(value);
                    }
                );
            });
        });
    }, useFormControlBySelectTreeOfData = function (domId, value, params) {
        layui.use(['xmSelect'], function () {
            useFormControlByXMSelect('#selectTree_' + domId, params, value, true, true,
                function (data) {
                    var value = 0;
                    if (data.length > 0) {
                        value = data[0].value;
                    }
                    $('#selectTree_hidden_' + domId).val(value);
                }
            );
        });
    }, useFormControlByXMSelect = function (element, dataList, initValue, isTree, isRadio, callback) {
        layui.use(['xmSelect'], function () {
            var xmSelect = layui.xmSelect,
                options = {
                    el: element,
                    search: false,
                    data: dataList,
                    tips: '请选择',
                    on: function (data) {
                        callback(data.arr);
                    }
                };
            if (isRadio) {
                options = Object.assign(options, {
                    radio: true,
                    clickClose: true
                });
            }
            if (initValue != null) {
                options['initValue'] = [initValue];
            }
            if (isTree) {
                options['tree'] = {
                    //是否显示树状结构
                    show: true,
                    //是否展示三角图标
                    showFolderIcon: true,
                    //默认展开节点的数组, 为 true 时, 展开所有节点
                    expandedKeys: [-1],
                    //是否严格遵守父子模式
                    strict: false,
                };
            }
            xmSelect.render(options);
        });
    }, useFormControlByUploadImage = function (api_path, field_name, modelId, field_ext) {
        layer.open({
            type: 2,
            title: '资源选择',
            content: '/index.php/Attachment/' + api_path,
            offset: 't',
            area: ['98%', '95%'],
            success: function (layero, index) {
                //拿到iframe元素
                var iframe = window['layui-layer-iframe' + index];
                var data = {field_name, modelId, field_ext, model_idx: index};
                //向此iframe层方法 传递参数
                iframe.child(JSON.stringify(data));

            }
        });
    }, useFormControlByUpload = function (field_name, modelId, field_ext, fn) {
        layui.use(['upload'], function () {
            var upload = layui.upload,
                accept, exts;
            if (field_ext === undefined || field_ext === null) {
                accept = 'images';
                exts = 'jpg|png|gif';
            } else {
                accept = 'file';
                exts = field_ext;
            }
            var options = {
                elem: '#PKBtn-Upload',
                url: '/index.php/Attachment/AdminUpload',
                headers: {token: ''},
                data: {modelId: modelId, field: field_name, accept: accept},
                multiple: true,
                accept: accept,
                exts: exts,
                before: function (obj) {
                    //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
                    //上传loading
                    layer.load();
                },
                done: function (apiResult) {
                    //关闭loading
                    layer.closeAll('loading');
                    apiResultHandler(apiResult, function (resData, resCount) {
                        fn(is_multiple, accept, resData, resCount);
                    });
                },
                error: function (index, upload) {
                    console.log('index', index);
                    console.log('upload', upload);
                    layer.closeAll('loading');
                }
            };
            if (accept === 'images') {
                options['acceptMime'] = 'image/*';
            }
            upload.render(options);
        });
    }, useFormByControl = function () {
        var dom_BDMaps = $('.pkcms_BaiDuMaps');
        if (dom_BDMaps.length > 0) {
            dom_BDMaps.each(function (index, element) {
                var id = $(element).data('id'),
                    name = $(element).data('name'),
                    value = $(element).data('value');
                $(element).html('\n' +
                    '<div class="layui-input-inline" style="width: 150px;">\n' +
                    '    <input type="text" placeholder="请选择百度地图坐标" class="layui-input" id="inputBaiDuMaps_' + id + '" name="' + name + '" value="' + value + '">\n' +
                    '</div>\n' +
                    '<div class="layui-inline" style="left: 0;">\n' +
                    '    <button type="button" class="layui-btn" id="BtnBaiDuMaps_' + id + '">浏览...</button>' +
                    '</div>');
                $('#BtnBaiDuMaps_' + id).on('click', function () {
                    useFormControlByBDMaps(id, '#inputBaiDuMaps_' + id);
                });
            });
        }
        var dom_colorPicker = $('.pkcms_colorpicker');
        if (dom_colorPicker.length > 0) {
            dom_colorPicker.each(function (index, element) {
                var id = $(element).data('id'),
                    name = $(element).data('name'),
                    value = $(element).data('value');
                $(element).html('\n' +
                    '<div class="layui-input-inline" style="width: 120px;">\n' +
                    '    <input type="text" placeholder="请选择颜色" class="layui-input" id="inputColorPicker_' + id + '" name="' + name + '" value="' + value + '">\n' +
                    '</div>\n' +
                    '<div class="layui-inline" style="left: -11px;">\n' +
                    '    <div id="divColorPicker_' + id + '"></div>\n' +
                    '</div>');
                useFormControlByColorPicker(id, value);
            });
        }
        var dom_date = $('.pkcms_date');
        if (dom_date.length > 0) {
            dom_date.each(function (index, element) {
                useFormControlByDateTime($(element));
            });
        }
        var dom_editor = $('.pkcms_editor');
        if (dom_editor.length > 0) {
            window.editor = [];
            dom_editor.each(function (index, element) {
                var id = $(element).attr('id');
                window.editor[id] = UE.getEditor(id);
                if (window.parent.hasOwnProperty('antispam') && window.parent.antispam.hasOwnProperty(id)) {
                    window.editor[id].ready(function () {
                        //赋值给UEditor
                        window.editor[id].setContent(window.parent.antispam[id]);
                    });
                }
            });
        }
        var dom_selectTree = $('.pkcms_selectTree');
        if (dom_selectTree.length > 0) {
            dom_selectTree.each(function (index, element) {
                var id = $(element).data('id'), source = $(element).data('source')
                    , value = $(element).data('value');
                $('#' + id).html('' +
                    '<input type="hidden" id="selectTree_hidden_' + id + '" name="' + $(this).data('name')
                    + '" value="' + value + '">' + '<div id="selectTree_' + id + '"></div>');
                if (typeof source === "string") {
                    console.log(source);
                    useFormControlBySelectTreeOfData(id, value, data[source]);
                } else {
                    useFormControlBySelectTree(id, value, $(this).data('api'));
                }
            });
        }
        var dom_select = $('.pkcms_select');
        if (dom_select.length > 0) {
            dom_select.each(function (index, element) {
                var id = $(element).attr('id');
                $('#' + id).html('<div id="select_' + id + '" lay-filter="select_' + id + '"></div>');
                useFormControlBySelect(id);
            });
        }
        var dom_switch = $('[lay-skin="switch"]');
        if (dom_switch.length > 0) {
            dom_switch.each(function (index, element) {
                var value = $(element).val();
                if ((value === '')) {
                    $(element).val(0);
                } else if (value === 1) {
                    $(element).attr('checked', true);
                }
            });
        }
        var dom_upload = $('.pkcms_upload');
        if (dom_upload.length > 0) {
            dom_upload.die().on('click', function () {
                var field_name = $(this).data('field'),
                    field_ext = $(this).data('exts'),
                    modelId = $(this).data('model'),
                    api_path;
                if (modelId === undefined) {
                    modelId = 0;
                    api_path = 'AdminGallery'
                } else {
                    api_path = 'AdminFiles';
                }

                useFormControlByUploadImage(api_path, field_name, modelId, field_ext);
            });
        }
    }, useModel = function (title, area, content, successFn) {
        layui.use(['layer'], function () {
            var layer = layui.layer;
            layer.open({
                type: 1,
                title: title,
                area: area,
                content: content,
                offset: 't',
                success: function (layero, index) {
                    successFn(index);
                }
            });

        });
    }, useModelByBtn = function (title, area, content, successFn, btnFn) {
        layui.use(['layer'], function () {
            var layer = layui.layer;
            layer.open({
                type: 1,
                title: title,
                area: area,
                content: content,
                btn: ['确认（关闭）'],
                offset: 't',
                success: function (layero, index) {
                    successFn(index);
                },
                yes: function (index, layero) {
                    btnFn(index);
                }
            });

        });
    }, getTableChecked = function (table, e, isTree, initTb, callback) {
        var selectId = [];
        if (isTree && (initTb != null)) {
            var checkedList = initTb.checkStatus();
            // console.log('checked', checkedList);
            if (checkedList.length > 0) {
                for (var i = 0; i < checkedList.length; i++) {
                    var tmp = checkedList[i];
                    selectId.push(tmp.id);
                }
            }
        } else {
            var checkStatus = table.checkStatus(e.config.id);
            if (checkStatus.data.length > 0) {
                for (var i = 0; i < checkStatus.data.length; i++) {
                    selectId.push(checkStatus.data[i].id);
                }
            }
        }
        if (selectId.length <= 0) {
            tipsMsg('请选择要操作的数据！');
        } else {
            callback({
                id: selectId
            });
        }
    }, getTableDataOfApiPath = function (domId) {
        var dom_table = $('#' + domId);
        var api_url = '/index.php/' + dom_table.data('get') + '/ApiByLists';
        var api_params = dom_table.data('params');
        if (typeof api_params != "undefined") {
            api_url += '?' + api_params;
        }
        var dom_query = $('input:text[name="query"]');
        if (dom_query.length === 1) {
            var val = dom_query.val();
            if (val !== '') {
                api_url += (api_url.indexOf('?') ? '?' : '&') + 'query=' + val;
            }
        }
        return api_url;
    }, useTpl = function (params, tpl_domId, callback) {
        layui.use(['laytpl'], function () {
            var layTpl = layui.laytpl,
                getTpl = doc.getElementById(tpl_domId).innerHTML;
            layTpl(getTpl).render(params, function (html) {
                callback(html, layTpl);
            });
        });
    }, useTplAppend = function (params, tpl_domId, view_domId) {
        useTpl(params, tpl_domId, function (html, tpl) {
            $('#' + view_domId).append(html);
        });
    };

    PKLayer.prototype.apiResultHandler = function (apiResult, fn) {
        apiResultHandler(apiResult, fn);
    }

    PKLayer.prototype.tipsMsg = function (str) {
        tipsMsg(str);
    };

    PKLayer.prototype.tipsAlert = function (str, icon) {
        tipsAlert(str, icon);
    };

    PKLayer.prototype.tipsConfirm = function (str, fn) {
        tipsConfirm(str, function () {
            fn();
        });
    };

    PKLayer.prototype.tipsConfirmByTwoBtn = function (title, options, yesFn, noFn) {
        layer.confirm(title, options, function (index) {
            yesFn(index);
        }, function () {
            noFn();
        });
    }

    PKLayer.prototype.apiPost = function (api_url, api_params, fn) {
        apiPost(api_url, api_params, function (resData, resCount) {
            fn(resData, resCount);
        });
    }

    PKLayer.prototype.apiGet = function (api_url, api_params, fn) {
        apiGet(api_url, api_params, function (resData, resCount) {
            fn(resData, resCount);
        });
    }

    PKLayer.prototype.dtree = function (fn) {
        layui.use(['dtree'], function () {
            var dtree = layui.dtree;
            fn(dtree);
        });
    };

    PKLayer.prototype.ImageView = function (domId) {
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            area: ['auto'],
            skin: 'layui-layer-nobg', //没有背景色
            shadeClose: true,
            content: $('#' + domId)
        });
    }

    PKLayer.prototype.useForm = function (onFormFn, onDomBtn) {
        useForm(function () {
            useFormByControl();
            useFormControlByBtnSubmit(function (paramsByForm) {
                onFormFn(paramsByForm);
            }, onDomBtn);
        });
    }

    PKLayer.prototype.useFormControlByParams = function (onFormFn, onDomBtn) {
        useFormControlByBtnSubmit(function (paramsByForm) {
            onFormFn(paramsByForm);
        }, onDomBtn);
    }

    PKLayer.prototype.useFormByControlAndSubmit = function (filter, fn) {
        layui.use(['form'], function () {
            var form = layui.form;
            useFormByControl();
            setTimeout(function () {
                form.render(null, filter);
                useFormControlByBtnSubmit(function (paramsByForm) {
                    fn(paramsByForm);
                }, 'lay-submit');
            }, 500);
        });
    }

    PKLayer.prototype.useFormByControl = function (filter, fn) {
        layui.use(['form'], function () {
            var form = layui.form;
            useFormByControl();
            setTimeout(function () {
                form.render(null, filter);
                fn();
            }, 500);
        });
    }

    PKLayer.prototype.useFormByTpl = function (params, domId_tpl, domId_view) {
        layui.use(['form'], function () {
            var form = layui.form;
            useTpl(params, domId_tpl, function (html, layTpl) {
                doc.getElementById(domId_view).innerHTML = html;
                useFormByControl();
                setTimeout(function () {
                    form.render(null, domId_view);
                }, 500);
            });
        });
    }

    PKLayer.prototype.useFormByStep = function (list_steps, height_steps, callback, domId_steps) {
        if (typeof domId_steps == "undefined") {
            domId_steps = 'stepForm';
        }
        layui.use(['form', 'element', 'step'], function () {
            var $ = layui.$
                , form = layui.form
                , step = layui.step
                , element_speed = layui.element;

            step.render({
                elem: '#' + domId_steps,
                filter: 'stepForm',
                width: '100%', //设置容器宽度
                stepWidth: '750px',
                height: height_steps,
                stepItems: list_steps
            });

            $('.pre').click(function () {
                step.pre('#stepForm');
            });

            $('.next').click(function () {
                step.next('#stepForm');
            });

            callback(form, step, element_speed);
        });
    };

    PKLayer.prototype.useFormBySelectFun = function (element, dataList, initValue, isTree, isRadio, callback) {
        useFormControlByXMSelect(element, dataList, initValue, isTree, isRadio, callback);
    }

    PKLayer.prototype.useFormBySelectSearch = function (element, is_radio, fnOfApi, fnOfRows, initValue) {
        initValue = typeof initValue == "undefined" ? [] : initValue;
        layui.use(['xmSelect'], function () {
            xmSelect.render({
                el: '#' + element,
                initValue: initValue,
                filterable: true,
                remoteSearch: true,
                radio: is_radio,
                paging: true,
                pageRemote: true,
                pageSize: 5,
                theme: {color: '#3E8AF4'},
                on: function (data) {
                    fnOfRows(data.arr);
                },
                remoteMethod: function (val, cb, show, pageIndex) {
                    fnOfApi(val, cb, show, pageIndex);
                }
            });
        });
    }

    PKLayer.prototype.useFormSetVal = function (elem, data) {
        layui.use(['form', 'layedit', 'laydate'], function () {
            var form = layui.form
                , layer = layui.layer
                , layedit = layui.layedit
                , laydate = layui.laydate;
            form.val(elem, data);
        });
    }

    PKLayer.prototype.useFormGetVal = function (elem, fn) {
        layui.use(['form', 'layedit', 'laydate'], function () {
            var form = layui.form
                , layer = layui.layer
                , layedit = layui.layedit
                , laydate = layui.laydate;
            var data = form.val(elem);
            fn(data);
        });
    }

    PKLayer.prototype.useModel = function (title, content, successFn, btnFn) {
        useModelByBtn(title, ["400px", "80%"], content,
            function (index) {
                successFn(index);
            }, function (index) {
                btnFn(index);
            });
    };

    PKLayer.prototype.useModelByTplBtn = function (title, domId_tpl, successFn, btnFn) {
        useTpl(Object.create(null), domId_tpl, function (html, tpl) {
            useModelByBtn(title, ["90%", "80%"], html,
                function (index) {
                    successFn(index);
                }, function (index) {
                    btnFn(index);
                });
        });
    };

    PKLayer.prototype.useModelByTpl = function (title, params, domId_tpl, successFn) {
        useTpl(params, domId_tpl, function (html, tpl) {
            useModel(title, ["80%", "80%"], html,
                function (index) {
                    successFn(index);
                });
        });
    }

    PKLayer.prototype.useModelByFrame = function (title, url) {
        layer.open({
            type: 2,
            title: title,
            content: url,
            offset: 't',
            area: ['98%', '95%'],
            success: function (layero, index) {
            }
        });
    }

    PKLayer.prototype.useOpenTab = function (elem, nodeId, title, iframe_src) {
        layui.use(['element', 'jquery'], function () {
            // 匹配选项卡是否存在
            var element = layui.element, matchTo = false,
                tabs = $('#' + elem + '>li');
            console.log('title', title);
            console.log('nodeId', nodeId);
            tabs.each(function (index) {
                var li = $(this),
                    layid = li.attr('lay-id');
                console.log('layid', layid);

                if (layid == nodeId) {
                    matchTo = true;
                    return;
                }
            });
            console.log('matchTo', matchTo);

            $('#tab_recovery').on('click', function () {
                alert('b');
            });

            // 如果未在选项卡中匹配到，则追加选项卡
            if (!matchTo) {
                element.tabAdd("content-tab", {
                    id: nodeId,
                    title: title,
                    content: "<iframe src='/index.php/" + iframe_src + "' id='" + nodeId + "_iframe' name='" + title + "_iframe' frameborder='0' class='layadmin-iframe'></iframe>"
                });
            }
            // 定位当前tabs
            element.tabChange("content-tab", nodeId);
        });
    }

    /**
     * 初始化后台界面侧边栏
     */
    PKLayer.prototype.useSideNav = function (elem, url) {
        layui.use(['element', 'NavBarSide'], function () {
            layui.NavBarSide({
                element: '#' + elem,
                url: '/index.php/' + url,
                type: 'post',
                shrink: false,
                onSelect: function (v) {
                    // console.log(v);
                }
            });
        });
    }

    PKLayer.prototype.getTableChecked = function (table, e, isTree, initTb, callback) {
        getTableChecked(table, e, isTree, initTb, callback);
    }

    PKLayer.prototype.getTableDataOfApiPath = function (domId) {
        return getTableDataOfApiPath(domId);
    }

    PKLayer.prototype.useTable = function (domId, api_url, customOptions, changeFN, toolFN,
                                           toolBarFN, isPage, api_param) {
        layui.use(['table'], function () {
            var $ = layui.$, table = layui.table;
            var domToolBar = '#table_toolBar';

            if (typeof api_param != "object") {
                api_param = Object.create(null);
            }
            if (typeof data == "object") {
                if (data.hasOwnProperty('table') && typeof data.table == "object") {
                    api_param = Object.assign(api_param, data.table);
                }
                if (data.hasOwnProperty('init') && typeof data.init == "object") {
                    api_param = Object.assign(api_param, data.init);
                }
            }

            var options = {
                elem: '#' + domId,
                url: api_url,
                //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                cellMinWidth: 60,
                // height: "full-220",
                text: {
                    none: '暂无相关数据'
                },
                limits: [10, 20, 50, 100],
                page: !(typeof isPage === "undefined"),
                toolbar: $(domToolBar).length === 1 ? domToolBar : false,
                defaultToolbar: ["filter"],
                where: api_param
            };

            options = $.extend(options, customOptions);

            table.render(options);
            // 监听事件
            changeFN(table);
            if ($(domToolBar).length > 0) {
                toolBarFN(table);
            }
            if ($('#table_tool').length > 0) {
                toolFN(table);
            }
            // 监听搜索
            var domBtn_search = layui.$('button[lay-search]');
            if (domBtn_search.length > 0) {
                domBtn_search.on('click', function () {
                    var tmp_params = Object.assign(Object.create(null), api_param, {
                        query: layui.$('input[name="query"]').val()
                    });
                    if (typeof data == "object" && typeof data.table == "object") {
                        tmp_params = Object.assign(tmp_params, data.table);
                    }
                    table.reload(domId, {
                        where: tmp_params
                    });
                    return false;
                });
            }
        });
    };

    PKLayer.prototype.useTableBySelect = function (domId, customOptions, callback) {
        layui.use('table', function () {
            var table = layui.table;
            table.render($.extend({
                elem: '#' + domId
                , page: false
            }, customOptions));

            //监听行单击事件（双击事件为：rowDouble）
            table.on('row(' + domId + ')', function (obj) {
                var data = obj.data;
                // layer.alert(JSON.stringify(data), {
                //     title: '当前行数据：'
                // });
                //标注选中样式
                obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
                callback(data);
            });

        });
    }

    PKLayer.prototype.useTableTree = function (domId, fieldIdName, fieldPidName, customOptions,
                                               changeFN, toolFN, toolBarFN, iconIndex, list_data) {
        layui.use(['treeTable'], function () {
            var treeTable = layui.treeTable,
                domToolBar = '#table_toolBar';
            var options = {
                elem: '#' + domId,
                tree: {
                    iconIndex: iconIndex === undefined ? 0 : iconIndex,           // 折叠图标显示在第几列
                    isPidData: true,        // 是否是id、pid形式数据
                    idName: fieldIdName,  // id字段名称
                    pidName: fieldPidName     // pid字段名称
                },
                toolbar: $(domToolBar).length === 1 ? domToolBar : false,
                defaultToolbar: ["filter"]
            };
            if (typeof list_data == "undefined") {
                options = $.extend(options, {url: getTableDataOfApiPath(domId)});
            } else {
                options = $.extend(options, {data: list_data});
            }
            options = $.extend(options, customOptions);

            // 渲染树形表格
            var insTb = treeTable.render(options);
            // 监听事件
            changeFN(treeTable, domId);
            if ($(domToolBar).length > 0) {
                toolBarFN(treeTable, insTb);
            }
            if ($('#table_tool').length > 0) {
                toolFN(treeTable);
            }
        });
    }

    PKLayer.prototype.useTableTreeBySelect = function (fieldIdName, fieldPidName, customOptions,
                                                       iconIndex, callback) {
        layui.use(['treeTable'], function () {
            var treeTable = layui.treeTable
                , domId = $('.PK-tableTree').attr('id')
                , domToolBar = '#table_toolBar'
                , api_get = getTableDataOfApiPath(domId);

            var options = {
                elem: '#' + domId,
                url: api_get,
                tree: {
                    iconIndex: iconIndex === undefined ? 0 : iconIndex,           // 折叠图标显示在第几列
                    isPidData: true,        // 是否是id、pid形式数据
                    idName: fieldIdName,  // id字段名称
                    pidName: fieldPidName     // pid字段名称
                },
                toolbar: $(domToolBar).length === 1 ? domToolBar : false,
                defaultToolbar: []
            };
            options = $.extend(options, customOptions);

            // 渲染树形表格
            var initTb = treeTable.render(options);
            if ($(domToolBar).length > 0) {
                treeTable.on('toolbar(' + domId + ')', function (e) {
                    getTableChecked(treeTable, e, true, initTb, function (api_params) {
                        callback(e.event, api_params);
                    });
                });
            }
        });
    }

    PKLayer.prototype.useTpl = function (params, domId_tpl, domId_view) {
        useTpl(params, domId_tpl, function (html, tpl) {
            doc.getElementById(domId_view).innerHTML = html;
        });
    }

    PKLayer.prototype.useTplCall = function (params, tpl_domId, view_domId, callback) {
        useTpl(params, tpl_domId, function (html, tpl) {
            doc.getElementById(view_domId).innerHTML = html;
            callback(tpl);
        });
    }

    PKLayer.prototype.useTplAppend = function (params, tpl_domId, view_domId) {
        useTplAppend(params, tpl_domId, view_domId);
    }

    PKLayer.prototype.useTplPrepend = function (params, tpl_domId, view_domId) {
        useTpl(params, tpl_domId, function (html, tpl) {
            $('#' + view_domId).prepend(html);
        });
    }

    PKLayer.prototype.useTplResult = function (params, tpl_domId, callback) {
        useTpl(params, tpl_domId, callback);
    }

    PKLayer.prototype.useTplFlow = function (api_path, list_limit, domId_tpl, domId_view) {
        layui.use(['flow'], function () {
            var flow = layui.flow;
            flow.load({
                elem: '#' + domId_view,
                end: '<div style="color: red;font-weight: bold;">木有了</div>',
                done: function (page, next) {
                    var params = {page: page, limit: list_limit};
                    if (typeof data.flowParams == "object") {
                        params = Object.assign(params, data.flowParams);
                    }
                    apiGet(api_path, params,
                        function (res_list, count) {
                            useTpl({list: res_list}, domId_tpl, function (html, tpl) {
                                next(html, page < Math.ceil(count / list_limit));
                            });
                        });
                }
            });
        });
    }

    PKLayer.prototype.useTree = function (domId, url, callback) {
        layui.use(['element', 'dtree', 'layer', 'jquery'], function () {
            var element = layui.element,
                dtree = layui.dtree;
            dtree.render({
                elem: "#" + domId,
                url: "/index.php/" + url,
                cache: false,
                dataStyle: "layuiStyle",
                type: "all",
                initLevel: 1,
                response: {
                    statusCode: 0,
                    message: "msg",
                    treeId: "id",
                    parentId: "parentId",
                    title: "name",
                    childName: "children",
                }
            });
            // 绑定节点点击
            dtree.on("node('" + domId + "')", function (obj) {
                callback(obj, element, dtree);
            });
        });
    }

    PKLayer.prototype.useTreeByData = function (domId, params, callback) {
        layui.use(['element', 'dtree', 'layer', 'jquery'], function () {
            var element = layui.element,
                dtree = layui.dtree;
            dtree.render({
                elem: "#" + domId,
                data: params,
                cache: false,
                dataStyle: "layuiStyle",
                type: "all",
                initLevel: 1,
                response: {
                    statusCode: 0,
                    message: "msg",
                    treeId: "id",
                    parentId: "parentId",
                    title: "name",
                    childName: "children",
                }
            });
            // 绑定节点点击
            dtree.on("node('" + domId + "')", function (obj) {
                callback(obj, element, dtree);
            });
        });
    }

    PKLayer.prototype.useUpload = function (field_name, modelId, field_ext, fn) {
        useFormControlByUpload(field_name, modelId, field_ext, fn);
    }

    win.PKLayer = new PKLayer();
}(window, document);